import Ember from 'ember';

export default Ember.Object.extend({
  timer: null,
  btnName: "Submit",
  btnMsg: Ember.computed(function() {
    return this.get('btnName');
  }),
  successMsg: "Success",
  failMsg: "Failed",
  saving: false,
  resetting: false,
  resultOk: false,
  setError: function(err) { // rr {fn:"", msg: ""}
    this.set('btnIcon', 'fa fa-exclamation-triangle');
    this.set('btnMsg', err.fn + ": " + err.msg);
    this.resetDelay();
  },
  is201: function(ae) {
    if (ae) {
      if (ae.name === "SyntaxError" && ae.message === "Unexpected end of input") {
        return true;
      }
    }
    return false;
  },
  resetDelay: function(ms) {
    var timer = this.get('timer');
    this.set('resetting', true);
    if (!ms) {
      ms = 3000;
    }
    if (timer) {
      window.clearTimeout(timer);
      this.set('timer', null);
    }
    var self = this;

    timer = window.setTimeout(function() {
      self.reset();
      window.clearTimeout(timer);
    }, ms);
  },
  save(controller) {
    console.log(controller);
    var args = Array.prototype.slice.call(arguments, 1);
    if (this.allowSubmit()) {
      this.startSaving();
      try {
        controller.saveThing(args);
      } catch (e) {
        console.log(e);
        this.failure();
      }
    }
  },
  startSaving: function() {
    this.set('btnMsg', 'Saving');
    this.set('btnIcon', 'fa fa-refresh fa-spin fa-fw');
    this.set('saving', true);
  },
  success: function() {
    this.set('btnMsg', this.get('successMsg'));
    this.set('btnIcon', 'fa fa-check');
    this.set('saving', false);
    this.resetDelay();
  },
  failure: function() {
    this.set('btnIcon', 'fa fa-close');
    this.set('failMsg', this.get('failMsg'));
    this.set('saving', false);
    this.resetDelay();
  },
  reset: function() {
    this.set('btnMsg', this.get('btnName'));
    this.set('btnIcon', null);
    this.set('resetting', false);
  },
  allowSubmit: function() {
    return !this.get('saving') && !this.get('resetting');
  },
  btnIcon: null
});
